using System;
using System.Collections.Generic;
using System.Text;
using ThaiLanguageTools.DataStruct;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace ThaiLanguageTools
{
    public class RomanizedLookup
    {
        internal const String RulesFile = @"ChangeRules.txt";

        XDict _dict;
        StringMapping _thaiToRoman;
        ChangeRuleList _ruleList;

        readonly List<SearchResult> EmptyResultList = new List<SearchResult>();


        public RomanizedLookup(XDict dict, StringMapping thaiToRoman)
        {
            _dict = dict;
            _thaiToRoman = thaiToRoman;
            _ruleList = ChangeRuleList.Load(RulesFile);
        }

        public List<SearchResult> FindByExactRoman(QueryInfo query)
        {
            List<String> thaiWords = _thaiToRoman.GetMappingsByB(query.Text);
            // Important optimization -- most of the time we stop here
            if (thaiWords.Count == 0) { return EmptyResultList; }

            List<SearchResult> results = new List<SearchResult>();
            foreach (String thaiWord in thaiWords)
            {
                List<XDictEntry> entries = _dict[thaiWord];
                foreach (XDictEntry entry in entries)
                {
                    results.Add(new SearchResult(query, entry));
                }
            }
            results = SearchResult.MergeResults(results);
            return results;
        }

        public QueryList GetQueries(String originalQueryText)
        {
            Debug.Assert(!String.IsNullOrEmpty(originalQueryText));

            QueryInfo originalQuery = new QueryInfo(originalQueryText);
            QueryList queries = new QueryList();
            queries.TryAddQuery(originalQuery);

            foreach (ChangeRule cr in _ruleList.Rules)
            {
                cr.ApplyRule(queries);
            }
            return queries;
        }

        internal ChangeRuleList ChangeRules
        {
            get { return _ruleList; }
            set
            {
                if (value == null) { throw new ArgumentNullException(); }
                _ruleList = value;
            }
        }

    }
}
